<?php
namespace Api\Controller;
use Common\Controller\ApibaseController;
use Common\Service\WxpayService;
use Common\Service\AlipayService;

/**
 * 需求
 * @package Api\Controller
 */
class RequireController extends ApibaseController {
    const MAX_DISTANCE=200000;/*限制范围，两万米内*/

    protected $require_model,$requireAns_model,$requireOrder_model,$msg_model;

    public function _initialize() {
        parent::_initialize();
        //$this->checkLogin();

        $this->require_model = D("Require");
        $this->requireAns_model = D("Require_ans");
        $this->requireOrder_model = D("Require_order");
        $this->msg_model = M("Message");
    }

    /**
     * 需求列表 
     * @link 访问地址 http://qiche.test2.yikeapp.cn/index.php?g=api&m=require&a=index
     * @see int type_id 需求分类：1为普通用户需求，2为商户需求，3为技师需求,可多传 以逗号分隔
     * @see int status 需求当前状态 1为已支付（未评价），3为已申请(未确认),0,4为未支付，1,6为已完成（已评价）
     * @see int page 当前分页数，默认1
     *
     * @see string lat 当前纬度
     * @see string lng 当前经度
     * 
     * @see string token 登录后获取的凭证
     * @see string userType 用户分类，默认为0 未登录用户为0，普通用户为1，商户为2 
     *
     * @see int me 是否我的需求，默认为0，为1时为显示我的需求
     * 
     * @return json 数据行排序为按该行排序数据listorder从大到小与ID从大到小排列
     *
     * 
     * {"status":1,"message":"查询成功！","data":[{"id":"1","user_id":"35","title":"轮胎爆了","contact":"","phone":"","image_ids":"1,2,3","status":"1","distance":"0","ans_status":"1","images":[{"id":"1","image":"http:\/\/test.qicheyanghu.com\/data\/upload\/file\/user\/20170616\/5943986c517cd.png"},{"id":"2","image":"http:\/\/test.qicheyanghu.com\/data\/upload\/file\/user\/20170616\/5943986c517cd.png"},{"id":"3","image":"http:\/\/test.qicheyanghu.com\/data\/upload\/file\/user\/20170616\/5943986c517cd.png"}],"username":"s2","avatar":"http:\/\/test.qicheyanghu.com\/data\/upload\/avatar\/user\/20170711\/5964870da08f5.png","avatar_small":"http:\/\/test.qicheyanghu.com\/data\/upload\/avatar\/user\/20170711\/5964870da08f5.png","create_time":"1970-01-01 08:00:00"}]}
     *
     *              status:1为正常状态，2为请重新登录，>2为数据异常
     *              info:提示信息
     *              data:返回数据
     *                  id:ID
     *                  user_id:用户ID
     *                  username:用户名
     *                  title:标题
     *                  contact:联系人
     *                  phone:联系人电话
     *                  image_ids:图片ID
     *                  images:需求图片
     *                      id:图片ID
     *                      image:图片网址
     *                  status:需求状态，1为显示0为隐藏
     *                  distance:距离
     *                  ans_status:需求订单状态：1为已支付，0为未支付，2为未申请,3为已申请，4为已通过，5为已打回,6为已完成（已评价），7为已删除 
     *                  avatar:头像
     *                  avatar_small:头像缩略图
     *                  create_time:需求创建时间
     *                          
     */
    public function index()
    {
        $type_id=I('type_id/d',0);
        $status=I('status/s',"");
        $me=I('me/d',0);

        $lat=I('lat/f',0);
        $long=I('lng/f',0);
        $distance=$this->getDistanceSql($lat,$long);

        $where=[];
        $where["t.status"]=1;

        $where["t.type_id"]=["exp","IN ($type_id)"];
        
        if ($status!=="") {
            $where["COALESCE(a.status,2)"]=["IN",$status];
        }
        if ($me==1){
            $where["t.user_id"]=$this->_userId;
        }else{
            $where["$distance"]=["LT",self::MAX_DISTANCE];
        }
        //dump($where);

        $join=$this->_getIndexJoin();
        $field=$this->_getIndexField($distance);

        $count=$this->require_model
            ->alias("t")
            ->join($join)
            ->where($where)
            ->field($field)
            //->fetchSql()
            ->count("DISTINCT(t.id)");

        //dump($count);
        $page = $this->page($count);

        $data=$this->require_model
            ->alias("t")
            ->join($join)
            ->where($where)
            ->field($field)
            ->group("t.id")
            ->order("t.id DESC")
            ->limit($page->firstRow, $page->listRows)
            //->fetchSql()
            ->select();
        //dump($data);

        if($data!==false){
            $this->ajaxReturn(1,$data,"查询成功！");
        }else{
            $this->ajaxReturn(0,array(),"查询错误");
        }
    }

    /**
     * 需求内容 
     * @link 访问地址 http://qiche.test2.yikeapp.cn/index.php?g=api&m=require&a=info
     * @see int id 需求ID
     *
     * @see string lat 当前纬度
     * @see string lng 当前经度
     * 
     * @see string token 登录后获取的凭证
     * @see string userType 用户分类，默认为0 未登录用户为0，普通用户为1，商户为2 
     * 
     * @return json 数据行排序为按该行排序数据listorder从大到小与ID从大到小排列
     *
     * 
     * {"status":1,"message":"查询成功！","data":{"id":"1","user_id":"35","title":"轮胎爆了","contact":"","phone":"","image_ids":"1,2,3","status":"1","distance":"0","ans_status":"1","images":[{"id":"1","image":"http:\/\/test.qicheyanghu.com\/data\/upload\/file\/user\/20170616\/5943986c517cd.png"},{"id":"2","image":"http:\/\/test.qicheyanghu.com\/data\/upload\/file\/user\/20170616\/5943986c517cd.png"},{"id":"3","image":"http:\/\/test.qicheyanghu.com\/data\/upload\/file\/user\/20170616\/5943986c517cd.png"}],"username":"s2","avatar":"http:\/\/test.qicheyanghu.com\/data\/upload\/avatar\/user\/20170711\/5964870da08f5.png","content":"轮胎爆了，求老司机救援","comment":"","comment_status":"0","complain":"啥会受到","complain_image_ids":"1,2,3","complain_images":[{"id":"1","image":"http:\/\/test.qicheyanghu.com\/data\/upload\/file\/user\/20170616\/5943986c517cd.png"},{"id":"2","image":"http:\/\/test.qicheyanghu.com\/data\/upload\/file\/user\/20170616\/5943986c517cd.png"},{"id":"3","image":"http:\/\/test.qicheyanghu.com\/data\/upload\/file\/user\/20170616\/5943986c517cd.png"}],"total":"","pay_status":"0","avatar_small":"http:\/\/test.qicheyanghu.com\/data\/upload\/avatar\/user\/20170711\/5964870da08f5.png","create_time":"1970-01-01 08:00:00"}}
     *
     *              status:1为正常状态，2为请重新登录，>2为数据异常
     *              info:提示信息
     *              data:返回数据
     *                  id:ID
     *                  user_id:用户ID
     *                  username:用户名
     *                  title:标题
     *                  contact:联系人
     *                  phone:联系人电话
     *                  image_ids:图片ID
     *                  images:需求图片
     *                      id:图片ID
     *                      image:图片网址
     *                  status:需求状态，1为显示0为隐藏
     *                  distance:距离
     *                  ans_status:需求订单状态
     *                  avatar:头像
     *                  avatar_small:头像缩略图
     *                  create_time:需求创建时间
     *
     *                  content:需求内容
     *                  comment:评论内容
     *                  comment_status:评论打星 1-5
     *                  complain:投诉内容
     *                  complain_image_ids:投诉内容附加图片
     *                  complain_images:投诉内容附加图片内容
     *                      id:图片ID
     *                      image:图片网址
     *                  total:支付价格
     *                  pay_status:0为未支付，1为已支付
     *                          
     */
    public function info()
    {
        $id=I('id/d',0);
        $lat=I('lat/f',0);
        $long=I('lng/f',0);
        $distance=$this->getDistanceSql($lat,$long);

        $where=[];

        //$where["t.status"]=1;
        $where["t.id"]=$id;
        //dump($where);

        $join=$this->_getInfoJoin();
        $field=$this->_getInfoField($distance);


        $data=$this->require_model
            ->alias("t")
            ->join($join)
            ->where($where)
            ->field($field)
            ->group("t.id")
            //->fetchSql()
            ->find();
        //dump($data);

        if($data!==false){
            $this->ajaxReturn(1,$data,"查询成功！");
        }else{
            $this->ajaxReturn(0,array(),"查询错误");
        }
    }

    /**
     * 发布需求
     * @link 访问地址 http://qiche.test2.yikeapp.cn/index.php?g=api&m=require&a=add
     * @see int type_id 需求分类：1为普通用户需求，2为商户需求，3为技师需求
     * @see string title 标题
     * @see string content 内容
     * @see string contact 联系人姓名
     * @see string phone 联系人电话
     * @see string image_ids 图片ID，逗号分隔
     * 
     *
     * @see string lat 当前纬度
     * @see string lng 当前经度
     * 
     * @see string token 登录后获取的凭证
     * @see string userType 用户分类，默认为0 未登录用户为0，普通用户为1，商户为2 
     * 
     * @return json 数据行排序为按该行排序数据listorder从大到小与ID从大到小排列
     *
     *
     *
     *
     *              status:1为正常状态，2为请重新登录，>2为数据异常
     *              info:提示信息
     *              data:返回数据
     *                      id: ID
     *                          
     */
    public function add(){
        $this->checkLogin();

        if ($this->_userType==2 && $this->_user['is_prepared']!=1) {
            $this->ajaxReturn(0,array(),"此商户暂不能下单！");
        }

        $data=I("post.");
        $data['user_id']=$this->_userId;
        if ($this->require_model->create($data)!==false) {
            if (isset($data['id'])) {
                $result=$this->require_model->save();
                $id=$data['id'];
            }else{
                $result=$this->require_model->add();
                $id=$result;
            }
            if ($result!==false) {
                $this->ajaxReturn(1,array("id"=>$id),"添加成功！");
            } else {
                $this->ajaxReturn(0,array(),"添加失败！");
            }
        } else {
            $this->ajaxReturn(0,array(),$this->require_model->getError());
        }
    }


    /**
     * 需求状态修改 如撤销发布等
     * @link 访问地址 http://qiche.test2.yikeapp.cn/index.php?g=api&m=require&a=status
     * @see int id 需求ID
     * 
     * @see string token 登录后获取的凭证
     * @see string userType 用户分类，默认为0 未登录用户为0，普通用户为1，商户为2
     *
     * @see int status 变更后状态,0为隐藏，1为显示
     * 
     * @return json 数据行排序为按该行排序数据listorder从大到小与ID从大到小排列
     *
     * 
     *
     *
     *              status:1为正常状态，2为请重新登录，>2为数据异常
     *              info:提示信息
     *              data:返回数据
     *                          
     */
    public function status(){
        $this->checkLogin();
        $id=I('id/d',0);
        $status=I('status/d',0);

        $where=[];
        $where["id"]=$id;
        $where["user_type"]=$this->_userType;
        $where["user_id"]=$this->_userId;

        $data=["status"=>$status];

        $result=$this->require_model->where($where)->field("status")->save($data);

        if ($result!==false) {
            $this->ajaxReturn(1,array(),"成功！");
        } else {
            $this->ajaxReturn(0,array(),"失败！");
        }
        
    }

    /**
     * 需求被商家接受
     * @link 访问地址 http://qiche.test2.yikeapp.cn/index.php?g=api&m=require&a=apply
     * @see int id 需求ID
     * 
     * @see string token 登录后获取的凭证
     * @see string userType 用户分类，默认为0 未登录用户为0，普通用户为1，商户为2
     *
     * 
     * 
     * @return json 
     *
     * 
     *
     *
     *              status:1为正常状态，2为请重新登录，>2为数据异常
     *              info:提示信息
     *              data:返回数据
     *                          
     */
    public function apply(){
        $this->checkLogin();

        if ($this->_user['is_prepared']!=1) {
            $this->ajaxReturn(0,array(),"此商户暂不能下单！");
        }

        $id=I('id/d',0);

        //开启事物
        $this->msg_model->startTrans();
        try {
            $require=$this->require_model
                ->field("user_id,title")
                ->find($id);
            //插入信息表
            $title = '您的需求- ' . $require['title'] . ' 已被接单，请打开我的需求查看具体信息';
            $content = '您的需求- ' . $require['title'] . ' 已被商户- '.$this->_user['name'].' 接单，请打开我的需求查看具体信息';
            $result = lt_add_message($title, $content, $require['user_id']);
            if ($result === false) {
                throw new Exception('插入信息表失败！');
            }
            //需求被商家接受
            $result=$this->_addStatus($id,3);
            if ($result === false) {
                throw new Exception('需求被商家接受失败！');
            }
            //$this->msg_model->rollback();
            $this->msg_model->commit();
        } catch (Exception $e) {
            $this->msg_model->rollback();
        }
        

        if ($result!==false) {
            $this->ajaxReturn(1,array(),"成功！");
        } else {
            $this->ajaxReturn(0,array(),"失败！");
        }
        
    }

    /**
     * 需求内容状态修改 如通过,打回等
     * @link 访问地址 http://qiche.test2.yikeapp.cn/index.php?g=api&m=require&a=ansStatus
     * @see int id 需求ID
     * @see int status 变更后状态,1为已支付，0为未支付，2为未申请,3为已申请，4为已通过，5为已打回,6为已完成（已评价），7为已删除
     * 
     * @see string token 登录后获取的凭证
     * @see string userType 用户分类，默认为0 未登录用户为0，普通用户为1，商户为2
     *
     * 
     * 
     * @return json 数据行排序为按该行排序数据listorder从大到小与ID从大到小排列
     *
     * 
     *
     *
     *              status:1为正常状态，2为请重新登录，>2为数据异常
     *              info:提示信息
     *              data:返回数据
     *                          
     */
    public function ansStatus(){
        $this->checkLogin();
        $id=I('id/d',0);
        $status=I('status/d',"");

        if (!in_array($status, [4,5])) {
            $this->ajaxReturn(0,array(),"状态错误！");
        }

        $result=$this->_setStatus($id,$status,3);

        if ($result!==false) {
            $this->ajaxReturn(1,array(),"成功！");
        } else {
            $this->ajaxReturn(0,array(),"失败！");
        }
        
    }

    /**
     * 需求的支付
     * @link 访问地址 http://qiche.test2.yikeapp.cn/index.php?g=api&m=require&a=pay
     * @see int id 需求ID
     * @see int total 支付金额
     * @see int pay_type 支付方式，1微信,2支付宝，3线下
     * 
     * @see string token 登录后获取的凭证
     * @see string userType 用户分类，默认为0 未登录用户为0，普通用户为1，商户为2
     * 
     * 
     * @return json 数据行排序为按该行排序数据listorder从大到小与ID从大到小排列
     *
     * 
     *
     *
     *              status:1为正常状态，2为请重新登录，>2为数据异常
     *              info:提示信息
     *              data:返回数据
     *                          
     */
    public function pay(){
        $this->checkLogin();
        $data=I("post.");

        $where=[];
        $where["require_id"]=$data['id'];
        $where["status"]=["IN","0,3,4"];
        $info=$this->requireAns_model->where($where)->field("user_id,id")->find();
        //dump($info);
        
        if (empty($info)) {
            $this->ajaxReturn(0,array(),"支付不存在！");
        }
        
        unset($data['id']);
        $data['ans_id']=$info['id'];
        $data['sn']=sp_get_order_sn();
        $data['pay_type']=$data["pay_type"];
        $data['status']=0;
        $data['create_time']=time();

        $result=$this->requireOrder_model->add($data);

        
        $order=$this->require_model
                ->field("user_id,title")
                ->find($where["require_id"]);
        $data['name']="一号点评-需求-".$order['title'];

        if ($result!==false) {
            switch ($data["pay_type"]) {
                case 1:
                    /*微信*/
                    $beforeOrder=(new WxpayService())->appPay($data['sn'], $data['name'], $data['total'],3);
                    break;
                case 2:
                    /*支付宝*/
                    $beforeOrder=(new AlipayService())->appPay($data['sn'], $data['name'], $data['total'],3);
                    break;
                
                default:
                    /*线下支付,直接确认支付成功*/
                    $beforeOrder=[];
                    $this->requireOrder_model->startTrans();
                    try {
                        $result=$this->requireOrder_model->where(["id"=>$result])->save(["status"=>1]);
                        if ($result === false) {
                            throw new Exception('需求订单支付失败！');
                        }
                        $result=$this->requireAns_model->where(["id"=>$info['id']])->save(["status"=>1]);
                        if ($result === false) {
                            throw new Exception('需求订单支付失败！');
                        }
                        //插入金额往来表
                        $result=M('PriceLog')->add(['user_id'=>$order['user_id'],'receive_user_id'=>$info['user_id'],'price'=>$data['total'],'create_time'=>time(),'type'=>1,'category'=>3]);
                        if ($result === false) {
                            throw new Exception('插入资金往来表失败！');
                        }
                        $this->requireOrder_model->commit();
                    } catch (Exception $e) {
                        $this->requireOrder_model->rollback();
                    }
                    break;
            }
            
            $this->ajaxReturn(1,$beforeOrder,"成功！");
        } else {
            $this->ajaxReturn(0,array(),"失败！");
        }
        
    }

    /**
     * 需求的评论
     * @link 访问地址 http://qiche.test2.yikeapp.cn/index.php?g=api&m=require&a=comment
     * @see int id 需求ID
     * 
     * @see string token 登录后获取的凭证
     * @see string userType 用户分类，默认为0 未登录用户为0，普通用户为1，商户为2
     *
     * @see string comment 评论内容
     * @see string comment_status 评论服务满意度 1-5星
     * 
     * @return json 数据行排序为按该行排序数据listorder从大到小与ID从大到小排列
     *
     * 
     *
     *
     *              status:1为正常状态，2为请重新登录，>2为数据异常
     *              info:提示信息
     *              data:返回数据
     *                          
     */
    public function comment(){
        $this->checkLogin();
        $id=I('id/d',0);

        $where=[];
        $where["id"]=$id;
        $where["user_type"]=$this->_userType;
        $where["user_id"]=$this->_userId;
        $where["status"]=1;

        $info=$this->require_model->where($where)->field("id")->find();

        if (empty($info)) {
            $this->ajaxReturn(0,array(),"需求错误！");
        }

        $data=I("post.");
        $data['status']=6;
        $where=["require_id"=>$info['id'],"status"=>1];
        $field="status,comment,comment_status";

        $result=$this->requireAns_model->where($where)->field($field)->save($data);

        if ($result!==false) {
            $this->ajaxReturn(1,array(),"成功！");
        } else {
            $this->ajaxReturn(0,array(),"失败！");
        }
    }

    /**
     * 需求的投诉
     * @link 访问地址 http://qiche.test2.yikeapp.cn/index.php?g=api&m=require&a=complain
     * @see int id 需求ID
     * 
     * @see string token 登录后获取的凭证
     * @see string userType 用户分类，默认为0 未登录用户为0，普通用户为1，商户为2
     *
     * @see string complain 投诉内容
     * @see string complain_image_ids 投诉图片ID
     * 
     * @return json 数据行排序为按该行排序数据listorder从大到小与ID从大到小排列
     *
     * 
     *
     *
     *              status:1为正常状态，2为请重新登录，>2为数据异常
     *              info:提示信息
     *              data:返回数据
     *                          
     */
    public function complain(){
        $this->checkLogin();
        $id=I('id/d',0);

        $where=[];
        $where["id"]=$id;
        $where["user_type"]=$this->_userType;
        $where["user_id"]=$this->_userId;
        $where["status"]=1;

        $info=$this->require_model->where($where)->field("id")->find();

        if (empty($info)) {
            $this->ajaxReturn(0,array(),"需求错误！");
        }

        $data=I("post.");
        $where=["require_id"=>$info['id'],"status"=>6];
        $field="complain,complain_image_ids";

        $result=$this->requireAns_model->where($where)->field($field)->save($data);

        if ($result!==false) {
            $this->ajaxReturn(1,array(),"成功！");
        } else {
            $this->ajaxReturn(0,array(),"失败！");
        }
        
    }

    /**
     * 技工发出求职需求的被雇佣
     * @link 访问地址 http://qiche.test2.yikeapp.cn/index.php?g=api&m=require&a=hire
     * @see int id 需求ID
     * 
     * @see string token 登录后获取的凭证
     * @see string userType 用户分类，默认为0 未登录用户为0，普通用户为1，商户为2
     *
     * 
     * @return json 数据行排序为按该行排序数据listorder从大到小与ID从大到小排列
     *
     * 
     *
     *
     *              status:1为正常状态，2为请重新登录，>2为数据异常
     *              info:提示信息
     *              data:返回数据
     *                          
     */
    public function hire(){
        $this->checkLogin();
        $id=I('id/d',0);

        $result=$this->_addStatus($id,4);

        if ($result!==false) {
            $this->ajaxReturn(1,array(),"成功！");
        } else {
            $this->ajaxReturn(0,array(),"失败！");
        }
        
    }

    /**
     * 需求记录删除
     * @link 访问地址 http://qiche.test2.yikeapp.cn/index.php?g=api&m=require&a=hire
     * @see int id 需求ID
     * 
     * @see string token 登录后获取的凭证
     * @see string userType 用户分类，默认为0 未登录用户为0，普通用户为1，商户为2
     *
     * 
     * @return json 数据行排序为按该行排序数据listorder从大到小与ID从大到小排列
     *
     * 
     *
     *
     *              status:1为正常状态，2为请重新登录，>2为数据异常
     *              info:提示信息
     *              data:返回数据
     *                          
     */
    public function delete(){
        $this->checkLogin();
        $id=I('id/d',0);

        $where=[];
        $where["require_id"]=$id;
        $where["user_type"]=$this->_userType;
        $where["user_id"]=$this->_userId;

        $data=["is_delete"=>1];

        $result=$this->requireAns_model->where($where)->field("is_delete")->save($data);

        if ($result!==false) {
            $this->ajaxReturn(1,array(),"成功！");
        } else {
            $this->ajaxReturn(0,array(),"失败！");
        }
        
    }

    /**
     * 商家已抢到订单
     * @link 访问地址 http://qiche.test2.yikeapp.cn/index.php?g=api&m=require&a=business_history
     * @see int type_id 需求分类：1为普通用户需求，2为商户需求，3为技师需求,可多传 以逗号分隔
     * @see int page 当前分页数，默认1
     *
     * @see string lat 当前纬度
     * @see string lng 当前经度
     * 
     * @see string token 登录后获取的凭证
     * @see string userType 用户分类，默认为0 未登录用户为0，普通用户为1，商户为2 
     *
     * 
     * @return json 
     *
     * 
     * {"status":1,"message":"查询成功！","data":[{"id":"1","user_id":"35","title":"轮胎爆了","contact":"","phone":"","image_ids":"1,2,3","status":"1","distance":"0","ans_status":"1","images":[{"id":"1","image":"http:\/\/test.qicheyanghu.com\/data\/upload\/file\/user\/20170616\/5943986c517cd.png"},{"id":"2","image":"http:\/\/test.qicheyanghu.com\/data\/upload\/file\/user\/20170616\/5943986c517cd.png"},{"id":"3","image":"http:\/\/test.qicheyanghu.com\/data\/upload\/file\/user\/20170616\/5943986c517cd.png"}],"username":"s2","avatar":"http:\/\/test.qicheyanghu.com\/data\/upload\/avatar\/user\/20170711\/5964870da08f5.png","avatar_small":"http:\/\/test.qicheyanghu.com\/data\/upload\/avatar\/user\/20170711\/5964870da08f5.png","create_time":"1970-01-01 08:00:00"}]}
     *
     *              status:1为正常状态，2为请重新登录，>2为数据异常
     *              info:提示信息
     *              data:返回数据
     *                  id:ID
     *                  user_id:用户ID
     *                  username:用户名
     *                  title:标题
     *                  contact:联系人
     *                  phone:联系人电话
     *                  image_ids:图片ID
     *                  images:需求图片
     *                      id:图片ID
     *                      image:图片网址
     *                  status:需求状态，1为显示0为隐藏
     *                  distance:距离
     *                  ans_status:需求订单状态：1为已支付，0为未支付，2为未申请,3为已申请，4为已通过，5为已打回,6为已完成（已评价），7为已删除 
     *                  avatar:头像
     *                  avatar_small:头像缩略图
     *                  create_time:需求创建时间
     *                          
     */
    public function business_history()
    {
        $type_id=I('type_id/d',0);

        $where=[];

        $lat=I('lat/f',0);
        $long=I('lng/f',0);
        $distance=$this->getDistanceSql($lat,$long);

        $where["t.type_id"]=["exp","IN ($type_id)"];
        $where["a.user_type"]=$this->_userType;
        $where["a.user_id"]=$this->_userId;
        $where["a.is_delete"]=0;

        $join=$this->_getIndexJoin();
        $field=$this->_getIndexField($distance);

        $count=$this->require_model
            ->alias("t")
            ->join($join)
            ->where($where)
            ->field($field)
            //->fetchSql()
            ->count("DISTINCT(t.id)");

        //dump($count);
        $page = $this->page($count);

        $data=$this->require_model
            ->alias("t")
            ->join($join)
            ->where($where)
            ->field($field)
            ->group("t.id")
            ->order("t.id DESC")
            ->limit($page->firstRow, $page->listRows)
            //->fetchSql()
            ->select();
        //dump($data);

        if($data!==false){
            $this->ajaxReturn(1,$data,"查询成功！");
        }else{
            $this->ajaxReturn(0,array(),"查询错误");
        }
    }

    protected function _getIndexJoin(){
        return [
            "LEFT JOIN __USER__ as u ON t.user_id=u.id AND t.type_id=1",
            "LEFT JOIN __BUSINESS__ as s ON t.user_id=s.id AND (t.type_id=2 OR t.type_id=3)",
            "LEFT JOIN __FILE__ as i ON FIND_IN_SET(i.id,t.image_ids) >0",/*图片*/
            "LEFT JOIN __REQUIRE_ANS__ a ON a.require_id=t.id AND a.status!=5",
            "LEFT JOIN __REQUIRE_ORDER__ o ON a.id=o.ans_id AND o.status=1"
        ];
    }

    protected function _getInfoJoin(){
        $join=$this->_getIndexJoin();
        $join[]="LEFT JOIN __FILE__ as f ON FIND_IN_SET(f.id,a.complain_image_ids) >0";/*评论图片*/
        $join[]="LEFT JOIN __BUSINESS__ as b ON a.user_id=b.id";/*接单商家*/
        return $join;
    }

    protected function _getIndexField($distance=""){
        $field = "t.id,t.user_id,t.title,t.contact,t.phone,t.image_ids,t.status,t.create_time,t.extra,t.type_id,
                COALESCE(a.status,2) as ans_status,
                GROUP_CONCAT( distinct (CONCAT_WS(',',i.id,i.path)) SEPARATOR '|') AS images,
                IF(t.type_id>1,s.name,u.username) as username,
                IF(t.type_id>1,s.logo,u.avatar) as avatar";
        if (!empty($distance)) {
            $field.=",$distance as distance";
        }

        return $field;
    }

    protected function _getInfoField($distance=""){
        $field=$this->_getIndexField($distance);
        return "
                $field,t.content,
                a.comment,a.comment_status,
                a.complain,a.complain_image_ids,a.is_resolve,a.id as ans_id,
                GROUP_CONCAT( distinct (CONCAT_WS(',',f.id,f.path)) SEPARATOR '|') AS complain_images,
                o.total,COALESCE(o.status,0) as pay_status,
                b.name as business_name,b.phone as business_phone,b.advantage,b.logo as bussiness_logo,
                IF(t.type_id>1,s.advantage,'') as user_advantage
                ";
    }

    protected function _getBusinessHistoryField($distance){
        $field=$this->_getIndexField($distance);
        return "
                $field,t.content,
                a.comment,a.comment_status,
                a.complain,a.complain_image_ids,
                GROUP_CONCAT( distinct (CONCAT_WS(',',f.id,f.path)) SEPARATOR '|') AS complain_images,
                o.total,COALESCE(o.status,0) as pay_status,
                b.name as business_name,b.phone as business_phone
                ";
    }

    protected function _addStatus($id,$status)
    {
        $data=[];
        $data["require_id"]=$id;
        $data["user_type"]=$this->_userType;
        $data["user_id"]=$this->_userId;
        $data["status"]=$status;
        $data["create_time"]=time();
        //dump($data);

        $result=$this->requireAns_model->create($data);
        $result=$this->requireAns_model->add([],[],true);

        if ($result===false) {
            return false;
        }else{
            return true;
        }
        
    }

    protected function _setStatus($id,$status,$fromStatus="")
    {
        $data=[];
        $data["require_id"]=$id;
        $data["status"]=$status;
        $data["create_time"]=time();
        //dump($data);

        $where=[];
        $where["id"]=$id;
        $where["user_type"]=$this->_userType;
        $where["user_id"]=$this->_userId;
        $count=$this->require_model->where($where)->count();
        if ($count>0) {
            $where=[];
            $where["require_id"]=$id;
            if (is_numeric($fromStatus)) {
                $where["status"]=$fromStatus;
            }
            $result=$this->requireAns_model->where($where)->save($data);
        }

        

        if ($result!==false && $result>0) {
            return true;
        }else{
            return false;
        }
        
    }

    public function getInfoData()
    {
        $join=$this->_getInfoJoin();
        $field=$this->_getInfoField();

        return [$join,$field];
    }

}